package net.JwtDemo.service;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.JwtDemo.PasswordEncoder.Md5PasswordEncoder;
import net.JwtDemo.dto.JsonResult;
import net.JwtDemo.dto.LoginUser;
import net.JwtDemo.entity.Role;
import net.JwtDemo.entity.UserInfo;
import net.JwtDemo.repository.UserInfoRepository;

import java.util.HashMap;
import java.util.List;

import javax.crypto.SecretKey;
import javax.security.sasl.AuthenticationException;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthService {
	
    private final UserInfoRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;
    private final AuthenticationManager authenticationManager;

    public JsonResult authenticate(LoginUser request) {
        log.debug("开始认证");        
        // 如果认证成功，生成令牌
	    UserInfo user;
	    try {
	    	user = userRepository.findByLoginName(request.getUsername())
	    			.orElseThrow(() -> new RuntimeException("没有找到用户"));
	    } catch (RuntimeException e) {
			return new JsonResult("1", e.getMessage());
		}
	    
	    if (!passwordEncoder.matches(request.getPassword(),  Md5PasswordEncoder.bytesToHex(user.getPasswd()))) {
	    	log.error("2，密码不正确");
	    	return new JsonResult("2", "密码不正确");
	    }
	    log.debug("密码校验成功");
        
        LoginUser loginUser = new LoginUser(user);
        String jwtToken = jwtService.generateToken(loginUser);
        log.debug("token:"+jwtToken);
        loginUser.setPassword("");
        loginUser.setUserName(user.getUserName());        
        
        HashMap map = new HashMap();
        
        map.put("token", jwtToken);
        map.put("user", loginUser);
        
        return new JsonResult(map);
    }
}